<template>
    <div class="register">
        <el-dialog title='注册' :style="{height: '100%'}" :visible.sync="display" @close="close_register"
                   width="35%" :close-on-click-modal='false' :modal="true">
            <!--注册登陆-->
            <span v-if="dialog_tag==='register'">
                <el-form :model="ruleForm" status-icon :rules="reg_rules" ref="ruleForm" label-width="100px"
                         class="demo-ruleForm">
                    <el-form-item label-width="5%">
                        <p style="font-size: 18px">登录过程中会用到短信，请准备好您的手机</p>
                    </el-form-item>
                    <el-form-item prop="reg_mobile" label-width="5%">
                        <!--下一步-->
                        <el-input type="text" v-model="ruleForm.reg_mobile" autocomplete="off" clearable
                                  prefix-icon="el-icon-phone-outline"
                                  placeholder="请输入手机号" :style="{width: '95%',height: '30px'}">
                        </el-input>
                    </el-form-item>
                    <el-form-item label-width="10%">
                        <el-button type="primary" @click="reg_next('ruleForm')"
                                   :style="{width: '90%', height: '45px', marginTop: '30px',fontSize: '16px'}">
                            下一步</el-button>
                    </el-form-item>
                </el-form>
            </span>

            <!--注册验证码校验登陆-->
            <span v-if="dialog_tag==='regCodeLogin'">
                <el-form :model="ruleForm" status-icon :rules="reg_rules" ref="ruleForm" label-width="100px"
                         class="demo-ruleForm">
                    <el-form-item prop="reg_mobile" label-width="5%">
                        <span :style="{fontSize: '18px',marginLeft: '5%',marginRight: '5%'}">手机号码</span>
                        <span :style="{fontSize: '17px',margin: '5%'}">{{ruleForm.reg_mobile}}</span>
                        <span @click="dialog_tag='register'"
                              :style="{color: '#409EFF',cursor: 'pointer',marginRight:'10%',float:'right',fontSize: '16px'}">
                            修改</span>
                    </el-form-item>

                    <el-form-item prop="reg_pass" label-width="9%">
                        <el-input type="password" v-model="ruleForm.reg_pass" autocomplete="off"
                                  clearable prefix-icon="el-icon-key" show-password
                                  placeholder="请输入密码" :style="{marginTop: '10px',width: '90%'}">
                        </el-input>
                    </el-form-item>

                    <el-form-item prop="reg_repass" label-width="9%">
                        <el-input type="password" v-model="ruleForm.reg_repass" autocomplete="off"
                                  clearable prefix-icon="el-icon-key" show-password
                                  placeholder="请确认密码" :style="{marginTop: '10px',width: '90%'}">
                        </el-input>
                    </el-form-item>

                    <el-form-item prop="reg_code" label-width="9%">
                        <el-input type="text" autocomplete="off" v-model="ruleForm.reg_code" clearable
                                  prefix-icon="el-icon-chat-line-round"
                                  placeholder="请输入收到的验证码" :style="{marginTop: '10px', width: '90%',height: '30px'}">
                            <template slot="append">
                                <span class="sms" @click="send_sms">{{ sms_interval }}</span>
                            </template>
                        </el-input>
                    </el-form-item>
                    <el-form-item label-width="10%">
                        <el-button type="primary" @click="register_check('ruleForm')"
                                   :style="{width: '90%', height: '45px',marginTop: '10px',fontSize: '16px'}">验证</el-button>
                    </el-form-item>
                </el-form>
            </span>

            <span slot="footer" class="dialog-footer">
            <el-button :style="{border: '0px'}" @click="go_dialog('login')">账号密码登陆</el-button>
            <el-button :style="{border: '0px'}" @click="go_dialog('thirdLogin')">其他方式登陆</el-button>
        </span>
        </el-dialog>
    </div>
</template>

<script>

    export default {
        name: "Register",
        data() {
            // 校验注册用户
            var validateRegMobile = (rule, value, callback) => {
                var phoneReg = /(^1[3-9][0-9]{9}$)/;
                if (value === '') {
                    callback(new Error('手机号不能为空'));
                } else if (!phoneReg.test(value)) {
                    callback(new Error('手机号码格式错误'));
                } else {
                    // 如果没有错误就可以回调
                    callback();
                }
            };
            // 检验密码
            var validateRegPass = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请输入密码'));
                } else if (value.length <= 3) {
                    callback(new Error('密码太短'));
                } else {
                    // 如果没有错误就可以回调
                    callback();
                }
            };
            // 检验确认密码
            var validateRePass = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请确认密码'));
                } else if (value !== this.ruleForm.reg_pass) {
                    callback(new Error('两次密码不一致'));
                } else {
                    // 如果没有错误就可以回调
                    callback();
                }
            };
            // 检验验证码
            var validateRegCode = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请输入验证码'));
                } else {
                    // 如果没有错误就可以回调
                    callback();
                }
            };
            return {
                display: true,

                // 表单数据
                ruleForm: {
                    reg_mobile: "",
                    reg_pass: "",
                    reg_repass: "",
                    reg_code: "",
                },

                // 注册校验
                reg_rules: {
                    reg_mobile: [
                        {validator: validateRegMobile, trigger: 'blur'}
                    ],
                    reg_pass: [
                        {validator: validateRegPass, trigger: 'blur'}
                    ],
                    reg_repass: [
                        {validator: validateRePass, trigger: 'blur'}
                    ],
                    reg_code: [
                        {validator: validateRegCode, trigger: 'blur'}
                    ]
                },

                // 根据值来判断渲染哪个dialog
                dialog_tag: "register",
                // 验证码框尾部显示
                sms_interval: '获取验证码',
                // 是否发送了验证码
                is_send: false,
            }
        },
        methods: {
            // 关闭dialog
            close_register() {
                // 子组件向父组件传参
                this.$emit('close')
            },
            // 跳转组件
            go_dialog(dialog) {
                this.$emit("go", dialog)
            },
            // 注册下一步
            reg_next(formName) {
                // 进行校验
                this.$refs[formName].validate((valid) => {

                    // 判断校验结果，布尔值
                    if (valid) {
                        this.dialog_tag = "regCodeLogin";

                        // 使用发送验证码接口
                        this.send_sms();
                    }
                });
            },
            // 注册校验
            register_check(formName) {
                // 对注册验证码进行校验
                this.$refs[formName].validate((valid) => {
                    // 判断校验结果，布尔值
                    if (valid) {
                        if(! this.ruleForm.reg_mobile){
                            // 更改显示层级
                            this.$message({
                                message: "请输入账号",
                                type: 'error',
                                duration: 2000,
                                onClose: () => {
                                    this.ruleForm.reg_pass = '';
                                    this.ruleForm.reg_repass = '';
                                }
                            });
                            $(".el-message--error").css("z-index", "8888");
                            return
                        }
                        if(this.ruleForm.reg_repass !== this.ruleForm.reg_pass){
                            // 更改显示层级
                            this.$message({
                                message: "两次密码不一致",
                                type: 'error',
                                duration: 2000,
                                onClose: () => {
                                    this.ruleForm.reg_pass = '';
                                    this.ruleForm.reg_repass = '';
                                }
                            });
                            $(".el-message--error").css("z-index", "8888");
                            return
                        }
                        const loading = this.$loading({
                            lock: true,
                            text: '正在注册...',
                            spinner: 'el-icon-loading',
                            background: 'rgba(0, 0, 0, 0.7)'
                        });
                        // 更改显示层级
                        $(".el-loading-mask").css("z-index", "8888");
                        setTimeout(() => {
                            this.$axios({
                                url: this.$settings.base_url + "/user/register",
                                method: "post",
                                data: {
                                    mobile: this.ruleForm.reg_mobile,
                                    password: this.ruleForm.reg_pass,
                                    re_password: this.ruleForm.reg_repass,
                                    code: this.ruleForm.reg_code
                                }
                            }).then(response => {
                                // 正确
                                if (!response.data.status) {
                                    let token = response.data["results"]["token"];
                                    if (token) {
                                        this.$cookies.set("token", token);
                                        let user_info = response.data["results"]["user_info"];
                                        this.$cookies.set("user_info", user_info);
                                        // 放到vuex中
                                        this.$store.state.userinfo = user_info;
                                        this.$store.state.token = token;
                                        console.log(this.$cookies.get("user_info"))

                                        loading.close()
                                    }
                                    // 子组件向父组件传参
                                    this.$emit('close')
                                }
                                // 错误
                                else {
                                    console.log(response.data)
                                    loading.close()
                                    // 更改显示层级
                                    this.$message({
                                        message: "注册失败",
                                        type: 'error',
                                        duration: 2000,
                                        onClose: () => {
                                            this.ruleForm.reg_pass = '';
                                            this.ruleForm.reg_repass = '';
                                        }
                                    });
                                    $(".el-message--error").css("z-index", "8888");
                                }
                            }).catch();
                        }, 1000);
                    }

                });
            },
            // 发送验证码
            send_sms() {
                // 判断是否发送了验证码
                if (this.is_send) return;  // 发送了就直接返回
                this.is_send = true; // 切换发送状态为已经发送
                this.sms_interval = "发送中...";
                this.$axios({
                    url: this.$settings.base_url + "/user/sms",
                    method: "post",
                    data: {
                        mobile: this.ruleForm.reg_mobile
                    }
                    // 回调成功
                }).then(response => {
                    // 判断数据状态码
                    if (response.data.status !== 0) {
                        this.sms_interval = "发送失败";
                        this.$message({
                            message: response.data.msg,
                            type: 'error',
                            duration: 2000,
                            onClose: () => {
                                this.ruleForm.reg_mobile = '';
                                this.sms_interval = "获取验证码";
                                this.is_send = false; // 重新恢复点击发送功能的条件
                            }
                        });
                        $(".el-message--error").css("z-index", "8888");
                    } else { // 发送验证码成功的逻辑

                        // 验证码发送成功，开始倒计时
                        let sms_interval_time = 60;

                        let timer = setInterval(() => {
                            if (sms_interval_time <= 1) {
                                clearInterval(timer);
                                this.sms_interval = "获取验证码";
                                this.is_send = false; // 重新恢复点击发送功能的条件
                            } else {
                                sms_interval_time -= 1;
                                this.sms_interval = `${sms_interval_time}秒后再发`;
                            }
                        }, 1000);
                    }

                }).catch(() => {
                    this.sms_interval = "发送过快";
                    this.$message({
                        message: "验证码发送发送频率过快",
                        type: 'error',
                        duration: 2000,
                        onClose: () => {
                            this.sms_interval = "获取验证码";
                            this.is_send = false; // 重新恢复点击发送功能的条件
                        }
                    });
                    $(".el-message--error").css("z-index", "8888");
                })

            },
        },
    }
</script>

<style scoped>
    .sms {
        color: orange;
        cursor: pointer;
        display: inline-block;
        width: 100px;
        text-align: center;
        user-select: none;
    }
</style>